// pages/kaituan/index.js
const WXAPI = require('apifm-wxapi')
let timer
Page({

  /**
   * 页面的初始数据
   */
  data: {
    countDown: '',
    currentData: {},
    product: {},
    promGroupDetailResultDtoList: [],
    restList: [],
    code: '' // 团购编号
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const code = options.code
    this.setData({
      code
    })
    this._initData(code)
  },
    /**
   * 生命周期函数--监听页面显示
   */
  // onShow: function () {
  //   this._initData(this.data.code)
  // },
  // 初始化数据
  _initData(code) {
    WXAPI.findByGroupNo(code).then(res => {
      const time = Date.parse(res.data.endTime) - Date.parse(new Date());
      let restArr = []
      const restLength = res.data.targetNum - res.data.promGroupDetailResultDtoList.length
      restArr.length = restLength
      this.setData({
        currentData: res.data,
        promGroupDetailResultDtoList: res.data.promGroupDetailResultDtoList,
        restList: restArr,
        countDown: time,
        num: res.data.targetNum - res.data.actNum
      })
      this._getProductDetail(res.data.itemNo)
    })
  },
  // 获取拼单商品详情
  _getProductDetail(goodsId) {
    WXAPI.goodsDetail(goodsId).then(res => {
      this.setData({
        product: res.data
      })
    })
  },
  toDetail(e) {
    const itemNo = e.currentTarget.dataset.itemno
    let code = this.data.code
    let groupNO = (code && code !== "undefined") ? code : ""
    wx.navigateTo({
      url: `/pages/goods-details/index?id=${itemNo}&groupNo=${groupNO}`
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const title = this.data.product.shopName || "快来一起参与拼团吧！"
    const imageUrl = this.data.product.narrowPicUrl || ""
    return {
      title,
      path: `pages/kaituan/index?code=${this.data.code}`,
      imageUrl
    }
  }
})